<?php

/**
 * banner页
 */
namespace backend\controllers;

use bc\controller\BackendController;
use bc\util\backend\Page;
use bc\model\ClassroomModel;
use bc\util\Uploader;

class ClassroomController extends BackendController
{
	
	
	public function actionIndex()
	{
		$model = new ClassroomModel();
		
		$params = '1 = 1';
		
		$page = $this->get('page', 1);
		$model->sort = 'update_time DESC';
		$list = $model->getList($params, $page, self::PAGE_SIZE);
		
		$total = $model->getTotal($params);
		
		$pagination = new Page($total, self::PAGE_SIZE);
		
		$view['list'] = $list;
		$view['pagination'] = $pagination;
		
		return $this->render('index', $view);
	}
	
	
	public function actionAdd()
	{
		return $this->render('add');
	}
	
	public function actionEdit()
	{
		$id = $this->get('id');
		if(!$id)
			$this->redirect('/');
	
		$model = new ClassroomModel();
		$row = $model->getRowById($id);
	
	
		if(!$row)
			$this->redirect('/');
	
		$view['row'] = $row;
	
		return $this->render('edit', $view);
	}
	
	public function actionSave()
	{
		
		if($this->getRequest()->getMethod() === 'POST' )
		{
			$model = new ClassroomModel();
			$id = $this->post('id', 0);
				
			$data['title'] = $this->post('title', '');
			$data['content'] = $this->post('content', '');
			$data['link'] = $this->post('link', '');
			$data['status'] = $this->post('status', '');
			$data['update_time'] = time();
				
			//Banner上传
			if($_FILES['image'])
			{
				$up = new Uploader( 'image' , $this->getUploadConfig() );
				$info = $up->getFileInfo();
				if($info['state'] === 'SUCCESS')
				{
					$data['image'] = str_replace(UPLOAD_PATH, '', $info['url']);
				}
					
			}
				
			if($id)
			{
				$model->modify($data, $id);
			}
			else
			{
				$data['create_time'] = time();
				$model->add($data);
			}
			$output['msg'] = '操作成功!';
				
		}
		else
		{
			$output['msg'] = '非法请求!';
		}
		
		$output['url'] = '/classroom';
		$this->forward($output);
	}
	
	/**
	 * @return array
	 */
	private function getUploadConfig()
	{
		//上传文件目录
		$path = UPLOAD_PATH . 'upload/';
		//上传配置
		$config = array(
				"savePath" => $path ,             //存储文件夹
				"maxSize" => 100000 ,                   //允许的文件最大尺寸，单位KB
				"allowFiles" => array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp" )  //允许的文件格式
		);
			
		//背景保存在临时目录中
		$config[ "savePath" ] = $path;
		return $config;
	}
}

